<?php

namespace app\index\controller;

use app\common\controller\Apicommon;
use app\common\controller\Excel;
use app\index\model\Device;
use app\index\model\GearRecord;
use app\index\model\MemberRecord;
use app\index\model\UnusualRecord;
use think\Db;

/**
 * 信息统计
 * @package app\index\controller
 */
class Information extends Apicommon
{
    use Excel;
    public function initialize()
    {
        //parent::initialize();
        header('Access-Control-Allow-Headers: content-type,authorization,token');
        header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
        header('Access-Control-Allow-Origin: *');
        if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
            echo 1;die;
        }
    }

    /**
     * 人员操作记录
     */
    public function member_record()
    {
        $where = [];
        $type = input('type');
        if (!empty($type)){
            if ($type == '开柜'){
                $where[] = ['record.type','eq',1];
            }elseif($type == '关柜'){
                $where[] = ['record.type','eq',0];
            }
        }
        $grade_name = input('grade_name');
        if (!empty($grade_name)){
            $where[] = ['grade.grade_name','eq',$grade_name];
        }
        $username = input('username');
        if (!empty($username)){
            $where[] = ['user.username|user.user_serial','eq',$username];
        }
        $start = input('start');
        if (!empty($start)){
            $where[] = ['record.create_time','>',strtotime($start)];
        }
        $end = input('end');
        if (!empty($end)){
            $where[] = ['record.create_time','<',strtotime($end)+86400];
        }
        $field = "
            record.id,
            record.gear_door,
            record.create_time,
            record.type,
            gear.gear_serial,
            door.door_serial,
            user.username,
            user.user_serial,
            grade.grade_name
        ";
        $member_record = MemberRecord::alias('record')->field($field)
            ->leftJoin('member_user user','user.id = record.uid')
            ->leftJoin('door','door.id = record.gear_door')
            ->leftJoin('gear','gear.id = door.gear_id')
            ->leftJoin('grade','grade.id = user.grade_id')
            ->order('record.id','desc')
            ->where($where)
            ->paginate(input('limit',10))->each(function ($item) {
                $item['type'] = $item['type'] == 1 ? '开柜' : '关柜';
                return $item;
            });

        $grade = db('grade')->field('grade_name')->select();
        $this->assign('grade',$grade);
        $this->assign('pages',$member_record->render());
        $this->assign('member_record',$member_record->items());
        return $this->fetch();
    }

    /**
     * 导出人员操作记录
     */
    public function member_record_export()
    {
        $field = "
            record.id,
            record.gear_door,
            record.create_time,
            record.type,
            gear.gear_serial,
            door.door_serial,
            user.username,
            user.user_serial,
            grade.grade_name
        ";
        $member_record = MemberRecord::alias('record')->field($field)
            ->leftJoin('member_user user','user.id = record.uid')
            ->leftJoin('door','door.id = record.gear_door')
            ->leftJoin('gear','gear.id = door.gear_id')
            ->leftJoin('grade','grade.id = user.grade_id')
            ->select();

        $data = [];
        foreach ($member_record as $key => $value){
            $temp['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
            $temp['type'] = $value['type'] == 1 ? '开柜' : '关柜';
            $temp['username'] = $value['username'];
            $temp['user_serial'] = $value['user_serial'];
            $temp['grade_name'] = $value['grade_name'];
            $temp['gear_serial'] = $value['gear_serial'];
            $temp['door_serial'] = $value['door_serial'];
            $data[] = $temp;
        }
        $this->exportExcel('操作记录',[
            '操作时间',
            '操作类型',
            '操作人员',
            '人员编号',
            '所属班组',
            '柜体编号',
            '柜门编号',
        ],$data);
    }

    /**
     * 设备存取记录
     * @param int $page 页码
     * @param int $limit 一页显示数量
     * @return mixed
     */
    public function gear_record()
    {
        $this->request->filter('trim');
        $query = $this->request->request();

        // 处理查询
        $where = [];
        // 按时间查询
        if (!empty($query['start'])) $where[] = ['record.action_time', 'egt', strtotime($query['start'])];
        if (!empty($query['end'])) $where[] = ['record.action_time', 'lt', strtotime($query['end'] . ' + 1 day')];
        // 按操作查询
        if (!empty($query['controller']) && in_array($query['controller'], ['取用', '归还'])) $where[] = ['record.action', '=', array_search($query['controller'], ['', '取用', '归还'])];
        // 按用户编号查询
        if (!empty($query['user_serial'])) $where[] = ['user.user_serial', '=', $query['user_serial']];
        // 按用户名查询
        if (!empty($query['username'])) $where[] = ['user.username', '=', $query['username']];
        // 按设备型号查询
        if (!empty($query['device_model'])) $where[] = ['device.device_model', '=', $query['device_model']];
        // 按设备名查询
        if (!empty($query['device_name'])) $where[] = ['device.device_name', '=', $query['device_name']];
        // 按设备编号查询
        if (!empty($query['device_serial'])) $where[] = ['device.device_serial', '=', $query['device_serial']];


        $gear_record = new GearRecord();
        $field = "
            record.id record_id,
            record.action_time,
            record.action,
            door.door_serial,
            device.device_name,
            device.device_model,
            device.device_serial,
            user.username,
            user.user_serial,
            gear.gear_serial gear_serial
        ";
        $record = $gear_record->alias('record')->field($field)
            ->leftJoin('device', 'device.id = record.device')
            ->leftJoin('member_user user', 'user.id = record.uid')
            ->leftJoin('door', 'door.id = record.gear_door')
            ->leftJoin('gear', 'gear.id = door.gear_id')
            ->order('record.id','desc')
            ->where($where)
            ->paginate(input('limit', 10), false);

        $record_data = $record->items();

        $this->assign('pages', $record->render());
        $this->assign('gear_record', $record_data);
        return $this->fetch();
    }

    /**
     * 导出设备存取记录
     */
    public function gear_record_export()
    {
        $gear_record = new GearRecord();
        $field = "
            record.id record_id,
            record.action_time,
            record.action,
            device.device_name,
            device.device_model,
            device.device_serial,
            user.username,
            user.user_serial,
            gear.gear_serial gear_serial,
            door.door_serial
        ";
        $record = $gear_record->alias('record')->field($field)
            ->leftJoin('device', 'device.id = record.device')
            ->leftJoin('member_user user', 'user.id = record.uid')
            ->leftJoin('door', 'door.id = record.gear_door')
            ->leftJoin('gear', 'gear.id = door.gear_id')
            ->select()->toArray();

        $data = [];
        foreach ($record as $item) {
            $temp['action_time'] = date('Y-m-d H:i:s',$item['action_time']);
            $temp['action_text'] = $item['action_text'];
            $temp['device_name'] = $item['device_name'];
            $temp['device_model'] = $item['device_model'];
            $temp['device_serial'] = $item['device_serial'];
            $temp['username'] = $item['username'];
            $temp['user_serial'] = $item['user_serial'];
            $temp['gear_serial'] = $item['gear_serial'];
            $temp['door_serial'] = $item['door_serial'];
            $data[] = $temp;
        }

        $this->exportExcel('设备存取记录',[
            '操作时间',
            '操作类型',
            '设备名称',
            '设备型号',
            '设备编号',
            '操作人员',
            '人员编号',
            '柜体编号',
            '柜门编号',
        ],$data);

    }

    /**
     * 设备异常记录
     * @param int $page 页码
     * @param int $limit 一页显示数量
     * @return mixed
     */
    public function unusual_record()
    {
        $this->request->filter('trim');
        $query = $this->request->request();

        // 处理查询
        $where = [];
        // 按时间查询
        if (!empty($query['start'])) $where[] = ['record.createtime', 'egt', strtotime($query['start'])];
        if (!empty($query['end'])) $where[] = ['record.createtime', 'lt', strtotime($query['end'] . ' + 1 day')];
        // 按操作查询
        if (!empty($query['type']) && in_array($query['type'], ['超时未还', '报废预警','柜门未关'])) $where[] = ['record.type', '=', array_search($query['type'], ['', '超时未还', '报废预警','柜门未关'])];
        // 按用户编号查询
        if (!empty($query['user_serial'])) $where[] = ['user.user_serial', '=', $query['user_serial']];
        // 按用户名查询
        if (!empty($query['username'])) $where[] = ['user.username', '=', $query['username']];
        // 按设备名查询
        if (!empty($query['device_name'])) $where[] = ['device.device_name', '=', $query['device_name']];
        // 按设备型号查询
        if (!empty($query['device_model'])) $where[] = ['device.device_model', '=', $query['device_model']];
        // 按设备编号查询
        if (!empty($query['device_serial'])) $where[] = ['device.device_serial', '=', $query['device_serial']];


        $unusual_record = new UnusualRecord();
        $field = "
            record.id record_id,
            record.createtime,
            record.type,
            record.door_id,
            device.device_name,
            device.device_model,
            device.device_serial,
            cate.name device_cate_name,
            user.username,
            user.user_serial,
            gear.gear_serial,
            door.door_serial
        ";
        $record = $unusual_record->alias('record')->field($field)
            ->leftJoin('device', 'device.id = record.device_id')
            ->leftJoin('device_category cate', 'cate.id = device.category_id')
            ->leftJoin('member_user user', 'user.id = record.user_id')
            ->leftJoin('gear', 'gear.id = record.gear_id')
            ->leftJoin('door', 'door.id = record.door_id')
            ->where($where)
            ->where('read','=',0)
            ->order('record_id','desc')
            ->paginate(input('limit', 10), false);
        $record_data = $record->items();

        // 设备型号列表
        $device_model = Device::distinct('device_model')->column('device_model');
        $device_name = Device::distinct('device_name')->column('device_name');

        $this->assign('pages', $record->render());
        $this->assign('row', $record_data);
        $this->assign('device_model', $device_model);
        $this->assign('device_name', $device_name);
        return $this->fetch();
    }

    /**
     * 导出设备存取记录
     */
    public function unusual_record_export()
    {
        $unusual_record = new UnusualRecord();
        $field = "
            record.id record_id,
            record.createtime,
            record.type,
            record.door_id,
            device.device_name,
            device.device_model,
            device.device_serial,
            cate.name device_cate_name,
            user.username,
            user.user_serial,
            gear.gear_serial,
            door.door_serial
        ";
        $record = $unusual_record->alias('record')->field($field)
            ->leftJoin('device', 'device.id = record.device_id')
            ->leftJoin('device_category cate', 'cate.id = device.category_id')
            ->leftJoin('member_user user', 'user.id = record.user_id')
            ->leftJoin('gear', 'gear.id = record.gear_id')
            ->leftJoin('door', 'door.id = record.door_id')
            ->where('read', '=', 0)
            ->order('record_id','desc')
            ->select()->toArray();

        $data = [];
        foreach ($record as $item) {
            $temp['createtime'] = date('Y-m-d H:i:s',$item['createtime']);
            $temp['type_text'] = $item['type_text'];
            $temp['device_name'] = $item['device_cate_name'] . '-' . $item['device_name'] . '-' . $item['device_model'];
            $temp['gear_serial'] = $item['gear_serial'];
            $temp['door_serial'] = $item['door_serial'];
            $temp['device_serial'] = $item['device_serial'];
            $temp['username'] = $item['username'];
            $temp['user_serial'] = $item['user_serial'];
            $data[] = $temp;
        }

        $this->exportExcel('设备异常记录',[
            '操作时间',
            '异常类型',
            '设备名称',
            '柜体编号',
            '柜门编号',
            '设备编号',
            '操作人员',
            '人员编号',
        ],$data);

    }

    /**
     * 设置异常信息为已读
     * @param int $id 记录ID
     * @return string
     */
    public function read_unusual($id = null)
    {
        $id = $id ?: $this->request->request('id');
        if (empty($id))
            $this->error_json('参数错误');

        $note = input('note');
        $record = UnusualRecord::get(['id'=>$id,'read'=>0]);
        if (!$record)
            $this->error_json('未找到可操作的记录');

        $record->read = 1;
        $record->note = $note;
        $record->save();
        $this->success_json('操作成功！');
    }

    /**
     * 处理异常信息，添加处理说明
     */
    public function add_read_note()
    {
        if (empty(input('id'))) {
            $this->error_json('参数错误');
        }
        $this->assign('record_id',input('id'));
        return $this->fetch();
    }

    /**
     * 仪器使用记录
     */
    public function used_record($device_id = null)
    {
        $where = $device_id ? ['device'=>$device_id] : [];
        $record = Db::name('used_record')->where($where)->order('id desc')->paginate(input('limit',10))->each(function ($item) {
            $user = Db::name('member_user')->where('id',$item['get_uid'])->whereOr('id',$item['back_uid'])->find();
            $item['get_username'] = '';
            $item['back_username'] = '';
            $item['get_grade'] = '';
            $item['back_grade'] = '';
            if (empty($user)){
                $item['get_username'] = '';
                $item['get_grade'] = '';
                $item['back_username'] = '';
                $item['back_grade'] = '';
            }else{
                $grade = Db::name('grade')->where('id',$user['grade_id'])->value('grade_name');
                if ($user['id'] == $item['get_uid']) {
                    $item['get_username'] = $user['username'];
                    $item['get_grade'] = $grade;
                }
                if ($user['id'] == $item['back_uid']) {
                    $item['back_username'] = $user['username'];
                    $item['back_grade'] = $grade;
                }
            }
            return $item;
        });
        $this->assign('record',$record->items());
        $this->assign('pages',$record->render());
        return $this->fetch('index/used_record');
    }

    /**
     * 已处理异常信息
     * @param int $page 页码
     * @param int $limit 一页显示数量
     * @return mixed
     */
    public function unusual_record_read()
    {
        $this->request->filter('trim');
        $query = $this->request->request();

        // 处理查询
        $where = [];
        // 按时间查询
        if (!empty($query['start'])) $where[] = ['record.createtime', 'egt', strtotime($query['start'])];
        if (!empty($query['end'])) $where[] = ['record.createtime', 'lt', strtotime($query['end'] . ' + 1 day')];
        // 按操作查询
        if (!empty($query['type']) && in_array($query['type'], ['超时未还', '报废预警','柜门未关'])) $where[] = ['record.type', '=', array_search($query['type'], ['', '超时未还', '报废预警','柜门未关'])];
        // 按用户编号查询
        if (!empty($query['user_serial'])) $where[] = ['user.user_serial', '=', $query['user_serial']];
        // 按用户名查询
        if (!empty($query['username'])) $where[] = ['user.username', '=', $query['username']];
        // 按设备名查询
        if (!empty($query['device_name'])) $where[] = ['device.device_name', '=', $query['device_name']];
        // 按设备型号查询
        if (!empty($query['device_model'])) $where[] = ['device.device_model', '=', $query['device_model']];
        // 按设备编号查询
        if (!empty($query['device_serial'])) $where[] = ['device.device_serial', '=', $query['device_serial']];


        $unusual_record = new UnusualRecord();
        $field = "
            record.id record_id,
            record.createtime,
            record.type,
            record.note,
            record.updatetime,
            record.door_id,            
            device.device_name,
            device.device_model,
            device.device_serial,
            cate.name device_cate_name,
            user.username,
            user.user_serial,
            gear.gear_serial,
            door.door_serial
        ";
        $record = $unusual_record->alias('record')->field($field)
            ->leftJoin('device', 'device.id = record.device_id')
            ->leftJoin('member_user user', 'user.id = record.user_id')
            ->leftJoin('device_category cate', 'cate.id = device.category_id')
            ->leftJoin('gear', 'gear.id = record.gear_id')
            ->leftJoin('door', 'door.id = record.door_id')
            ->where($where)
            ->where('read','=',1)
            ->order('updatetime','desc')
            ->paginate(input('limit', 10), false);
        $record_data = $record->items();

        // 设备型号列表
        $device_model = Device::distinct('device_model')->column('device_model');
        $device_name = Device::distinct('device_name')->column('device_name');

        $this->assign('pages', $record->render());
        $this->assign('row', $record_data);
        $this->assign('device_model', $device_model);
        $this->assign('device_name', $device_name);
        return $this->fetch();
    }

    /**
     * 导出已处理异常信息
     */
    public function unusual_record_read_export()
    {
        $unusual_record = new UnusualRecord();
        $field = "
            record.id record_id,
            record.createtime,
            record.type,
            record.note,
            record.door_id,
            record.updatetime,
            device.device_name,
            device.device_model,
            device.device_serial,
            cate.name device_cate_name,
            user.username,
            user.user_serial,
            gear.gear_serial,
            door.door_serial
        ";
        $record = $unusual_record->alias('record')->field($field)
            ->leftJoin('device', 'device.id = record.device_id')
            ->leftJoin('device_category cate', 'cate.id = device.category_id')
            ->leftJoin('member_user user', 'user.id = record.user_id')
            ->leftJoin('gear', 'gear.id = record.gear_id')
            ->leftJoin('door', 'door.id = record.door_id')
            ->where('read', '=', 1)
            ->select()->toArray();

        $data = [];
        foreach ($record as $item) {
            $temp['createtime'] = date('Y-m-d H:i:s',$item['createtime']);
            $temp['updatetime'] = date('Y-m-d H:i:s',$item['updatetime']);
            $temp['type_text'] = $item['type_text'];
            $temp['device_name'] = $item['device_cate_name'] . '-' . $item['device_name'] . '-' . $item['device_model'];
            $temp['gear_serial'] = $item['gear_serial'];
            $temp['door_serial'] = $item['door_serial'];
            $temp['device_serial'] = $item['device_serial'];
            $temp['username'] = $item['username'];
            $temp['user_serial'] = $item['user_serial'];
            $temp['note'] = $item['note'];
            $data[] = $temp;
        }

        $this->exportExcel('已处理异常记录',[
            '操作时间',
            '处理时间',
            '异常类型',
            '设备名称',
            '柜体编号',
            '柜门编号',
            '设备编号',
            '操作人员',
            '人员编号',
            '处理说明',
        ],$data);

    }
}
